package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.EnergyLevelDao;
import com.juyu.miliao.api.dao.mysql.UserCountDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.redis.EnergyLevelRedisDao;
import com.juyu.miliao.api.domain.BillDetailEnergy;
import com.juyu.miliao.api.domain.EnergyLevel;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.api.util.SystemMessageUtil;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletionException;

/**
 * wbf
 * 用户能量业务方法
 */
@Service
public class EnergyLevelService {

    private final Logger logger = LoggerFactory.getLogger("energyLevel");
    @Resource
    private EnergyLevelDao energyLevelDao;
    @Resource
    private UserCountDao userCountDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private EnergyLevelRedisDao energyLevelRedisDao;
    @Resource
    private SystemMessageUtil systemMessageUtil;

    private static final long robotSendMessageUserId = 12890000;

    /**
     * 返回能量值对应的当前等级信息、称号
     * @return
     */
    public EnergyLevel getUserEnergyLevel(int energySum){
        List<EnergyLevel> energyLevelList = energyLevelDao.getUserEnergyLevelList();
        return countEnergyLevel(energyLevelList,energySum);
    }

    /**
     * 增加用户能量
     * @param userId 增加能量用户id
     * @param levelType 增加能量类型 1:在线时长 2评论动态 3点赞动态 4分享动态 5充值寻币 6购买vip
     * @param energy 增加能量值
     * @return 返回成功数
     */
    public int addUserEnergyLevel(long userId, EnergyLevelType levelType , int energy){
        logger.info("userId:"+userId+"---levelType:"+levelType.getCode()+"---energy:"+energy);
        //返回成功数
        int temp = 0;
        //增加能量类型是否有每日限制
        //该能量类型每日最大获取能量数
        int maxEnergy = levelType.getMaxValue();
        //没有限制直接保存
        if(maxEnergy == 0){
            temp = energyLevelDao.insertBillDetailEnergy(userId,levelType.getCode(),energy);
            if(temp > 0){
                temp = userCountDao.addUserEnergySum(userId,energy);
            }
            energyLevelRedisDao.addEnergyLevelByType(levelType.getCode(),userId,energy);
            return temp;
        }
        //判断用户是否是vip，如果是 最大限制、能量值翻倍
        User user = userInfoDao.getUserInfoById(userId);
        if(user.getIsVip() == 1 || user.getIsSvip()==1 || user.getIsPlatinumVip()==1){
            maxEnergy = maxEnergy * 2;
            energy = energy * 2;
        }
        int isSaveEnergy = energyLevelRedisDao.getEnergyLevelByType(levelType.getCode(),userId);
        if(isSaveEnergy >= maxEnergy){
            return temp;
        }
        //如果加上当前能量 最大能量值超过限制，则减少本次获取的能量值
        if((energy + isSaveEnergy) > maxEnergy){
            energy = maxEnergy - isSaveEnergy;
        }
        temp = energyLevelDao.insertBillDetailEnergy(userId,levelType.getCode(),energy);
        if(temp > 0){
            temp = userCountDao.addUserEnergySum(userId,energy);
        }
        energyLevelRedisDao.incrementEnergyLevelByType(levelType.getCode(),userId,energy);
        //当用户到11级时，会系统发的消息，消息内容“您已结算专属客服，请添加微信：xxxxxxx。”
        EnergyLevel energyLevel = getUserEnergyLevel(user.getEnergySum()+energy);
        if(energyLevel.getEnergyGrade()==11){
            Boolean user11Grade = energyLevelRedisDao.isMember11UserGrade(userId);
            if(user11Grade!=null && !user11Grade){
                user11GradeSystemMessage(userId);
                energyLevelRedisDao.add11UserGrade(userId);
            }
        }
        return temp;
    }

    /**
     * 当用户到11级时，会系统发的消息，消息内容“您已解锁专属客服，请添加微信：XXGF55555。”
     * @param userId
     */
    public void user11GradeSystemMessage(long userId){
        String msg = SpendSystemMessage.USER_UPGRADE_ELEVEN_SEND_MESSAGE.getMessage();
        systemMessageUtil.sendSystemMessageByUser11(userId,msg);
//    JSONObject body = new JSONObject();
//        //开发者扩展字段
//        JSONObject ext = new JSONObject();
//        try {
//            String temp = NetEaseCloudUserService.getSendMsg(userId, robotSendMessageUserId,
//                        EnumType.TEXT_MESSAGE.state, body.toString(), ext.toString(), "");
//                if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
//                    logger.error("发送用户到11级消息异常-云信：userId={},message={}", userId, temp);
//                }
//            } catch (Exception e) {
//                logger.error("发送用户到11级消息异常：userId={},error={}", userId, e);
//            }

    }

    /**
     * 获取用户能量明细
     * @param userId
     * @return
     */
    public List<BillDetailEnergy> getUserBillDetailEnergy(long userId, Integer page, Integer pageSize){
        int startNum = PageUtil.getOffset(page, pageSize);
        return energyLevelDao.getUserBillDetailEnergy(userId, startNum, pageSize);
    }


    /**
     * 工具方法
     * 获取用户当前等级、下一等级要求
     * @param energyLevelList 等级列表
     * @param energySum 要计算的能量值
     * @return
     */
    public EnergyLevel countEnergyLevel(List<EnergyLevel> energyLevelList,int energySum){
        EnergyLevel energyLevel = new EnergyLevel();
        //是否当前经验大于最大等级
        if(energySum >= energyLevelList.get(energyLevelList.size()-1).getEnergyValue()){
            energyLevel = energyLevelList.get(energyLevelList.size()-1);
            energyLevel.setUserEnergyNextLevelValue(999999);
            return energyLevel;
        }
        // 是否当前经验是0
        if(energySum == 0){
            energyLevel = energyLevelList.get(0);
            energyLevel.setUserEnergyNextLevelValue(energyLevelList.get(1).getEnergyValue());
            return energyLevel;
        }

        for (int i = 0; i < energyLevelList.size(); i++) {
            if(energySum<energyLevelList.get(i).getEnergyValue()){
                energyLevel = energyLevelList.get(i-1);
                energyLevel.setUserEnergyNextLevelValue(energyLevelList.get(i).getEnergyValue());
                break;
            }
        }
        return energyLevel;
    }

    /**
     * 获取能量等级列表
     * @return
     */
    public List<EnergyLevel> getEnergyList() {
        return energyLevelDao.getUserEnergyLevelList();
    }

    /**
     * 根据用户获取
     * 等级座驾信息
     * @param userId
     * @return
     */
    public JSONArray getVehicleList(long userId) {
        JSONArray jsonArray = new JSONArray();
        User user = userInfoDao.getUserInfoById(userId);
        EnergyLevel energyLevel = getUserEnergyLevel(user.getEnergySum());
        List<EnergyLevel> levelList = energyLevelDao.getLevelInfoList();
        levelList.forEach(level->{
            JSONObject json = new JSONObject();
            json.put("id",level.getId());
            json.put("vehicleName",level.getVehicleName());
            json.put("vehiclePic",level.getVehiclePic());
            json.put("vehicleVideo",level.getVehicleVideo());
            if(user.getVehicleId() == level.getId()){
                json.put("isSelect","true"); //是否选中
            }else{
                json.put("isSelect","false"); //是否选中
            }
            if(energyLevel.getEnergyGrade() >= level.getMinGrade()){
                json.put("isOptions","true"); //是否可选
            }else{
                json.put("isOptions","false"); //是否可选
            }
            json.put("lockLevel",level.getMinGrade());
            json.put("userId",user.getUserId());
            jsonArray.add(json);
        });
        return jsonArray;
    }

    public JSONObject getLevelDifference(long userId,int levelId) {
        JSONObject json = new JSONObject();
        User user = userInfoDao.getUserInfoById(userId);
        EnergyLevel userEnergyLevel = getUserEnergyLevel(user.getEnergySum());
        List<EnergyLevel> levelList = energyLevelDao.getLevelInfoList();
        EnergyLevel findEnergyLevel = levelList.stream().filter(i->i.getId()==levelId).findAny().orElse(null);
        if(findEnergyLevel==null){
            throw new ConsumeRuntimeException("levelId错误");
        }
        if(userEnergyLevel.getEnergyGrade() >= findEnergyLevel.getMinGrade()){
            json.put("isOpenLevel","true");//是否解锁
            json.put("difference","0");//差多少能量解锁
        }else{
            json.put("isOpenLevel","false");
            EnergyLevel energyLevel = energyLevelDao.selectEnergyLevelInfoByEnergyGrade(findEnergyLevel.getMinGrade());
            json.put("difference",energyLevel.getEnergyValue()-user.getEnergySum());
        }
        json.put("energyGrade",userEnergyLevel.getEnergyGrade());//用户当前能量
        json.put("findLevel",findEnergyLevel.getId());//查询levelId
        json.put("levelMixGrade",findEnergyLevel.getMinGrade());//查询的level最小要求等级
        json.put("levelMaxGrade",findEnergyLevel.getMaxGrade());//查询的level最大要求等级
        return json;
    }
}
